package controllers

import java.io.File

import dao._
import javax.inject.Inject
import play.api.libs.json.Json
import play.api.mvc._
import utils.Utils

import scala.concurrent.ExecutionContext.Implicits.global
import tool._
import models.Tables._
import org.joda.time.format.DateTimeFormat
import utils.Utils.{Info, Sender}

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.Future
import utils.Implicits._

/**
  * Created by yz on 2018/8/20
  */
class AdminController @Inject()(cc: ControllerComponents, formTool: FormTool,
                                tool: Tool, missionDao: MissionDao, extraDataDao: ExtraDataDao,
                                trashDao: TrashDao, pdfInfoDao: PdfInfoDao) extends AbstractController(cc) {


  def userDataBefore = Action { implicit request =>
    Ok(views.html.admin.userData())
  }

  def getAllMission = Action.async { implicit request =>
    missionDao.selectAll.zip(extraDataDao.selectAll).
      zip(trashDao.selectAll).map { case ((missionRows, extraRows), trashs) =>
      val extraMap = extraRows.map(x => (x.id, x)).toMap
      val trashMap = trashs.map { x =>
        val isDelete = if (x.exist == 0) "否" else "是"
        (x.id, isDelete)
      }.toMap
      val t2s = missionRows.map(x => (x, extraMap.getOrElse(x.id, tool.getEmptyExtraDataRow(x.id))))
      val array = Utils.getArrayByT2s(t2s).map { x =>
        x + ("isDelete" -> trashMap(x("id").toInt))
      }
      Ok(Json.toJson(array))
    }
  }

  def downloadDb = Action.async { implicit request =>
    missionDao.selectAll.zip(extraDataDao.selectAll).
      zip(trashDao.selectAll).map { case ((missionRows, extraRows), trashs) =>
      val extraMap = extraRows.map(x => (x.id, x)).toMap
      val trashMap = trashs.map { x =>
        val isDelete = if (x.exist == 0) "否" else "是"
        (x.id, isDelete)
      }.toMap
      val lines = ArrayBuffer[ArrayBuffer[String]]()
      val headers = ArrayBuffer("样品号", "姓名", "年龄", "AST", "ALT", "PLT", "风险得分", "结果", "时间", "是否删除",
        "送检单位", "地址", "性别", "送检科室", "申请医生", "门诊/住院号", "采样时间", "送检时间",
        "样本类型", "样本状态", "标题", "检验", "审核", "检验日期", "报告日期")
      lines += headers ++= missionRows.map { x =>
        val isDelete = trashMap(x.id)
        val extra = extraMap.getOrElse(x.id, tool.getEmptyExtraDataRow(x.id))
        ArrayBuffer(extra.sampleId, extra.name, x.age, x.ast, x.alt, x.plt, x.score, x.result, x.endTime, isDelete,
          extra.unit, extra.address, extra.sex, extra.office, extra.doctor, extra.number, extra.sampleTime, extra.submitTime,
          extra.sampleType, extra.sampleStatus, extra.title, extra.reporter, extra.checker, extra.submitTime,
          extra.reportDate)
      }.sortBy(_ (0))
      val tmpDir = tool.createTempDirectory("tmpDir")
      val file = new File(tmpDir, "db.txt")
      lines.map(_.mkString("\t")).toFile(file)
      Ok.sendFile(file, onClose = () => {
        Utils.deleteDirectory(tmpDir)
      }).withHeaders(
        CONTENT_DISPOSITION -> s"attachment; filename=${
          file.getName
        }",
        CONTENT_TYPE -> "application/x-download"
      )

    }
  }

}
